<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    okText="生成代码"
  >
    <BasicForm @register="registerForm" />
    <generateCodeDow @register="registerCodeDowModal" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onUnmounted, reactive } from 'vue';
  import { Progress } from 'ant-design-vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { codeGenformSchema } from './generateFrom.data';
  import { codeFileGenerator } from '/@/api/generate/generate.api';
  import generateCodeDow from './generateCodeDow.vue';

  export default defineComponent({
    name: 'DeptModal',
    components: { BasicModal, BasicForm, Progress, generateCodeDow },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      let sortable1: any;

      let initTime: any;
      const [registerCodeDowModal, { openModal }] = useModal();
      onUnmounted(() => {
        clearTimeout(initTime);
        if (sortable1) {
          sortable1.destroy();
        }
      });

      const isUpdate = ref(true);

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 22 },
        schemas: codeGenformSchema,
        showActionButtonGroup: false,
        compact: true,
      });

      const [registerModal, { setModalProps, closeModal, changeOkLoading }] = useModalInner(
        async (data) => {
          resetFields();
          setModalProps({ confirmLoading: false });
          isUpdate.value = !!data?.isUpdate;
          setFieldsValue({
            ...data.record,
          });
        },
      );

      const getTitle = computed(() => '代码生成');

      async function handleSubmit() {
        try {
          changeOkLoading(true);
          const values = await validate();
          await codeFileGenerator({ mainId: values.id, packagePath: values.packagePath }).then(
            (res) => {
              openModal(true, {
                res,
              });
            },
          );
          closeModal();
          // emit('success');
        } finally {
          changeOkLoading(false);
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerCodeDowModal,
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
